package com.cgy.utils.qrcode;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码工具类
 *
 * @author CHTK
 */
public class QrCodeHelper {
    /**
     * * 解析二维码解析,此方法是解析Base64格式二维码图片
     *
     * @param baseStr base64字符串,data:image/png;base64开头的
     * @return
     */
    public static String deEncodeByBase64(String baseStr) {
        BufferedImage image = null;
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] b = null;
        try {
            int i = baseStr.indexOf("data:image/png;base64,");
            //去掉base64图片的data:image/png;base64,部分才能转换为byte[]
            baseStr = baseStr.substring(i + "data:image/png;base64,".length());
            //baseStr转byte[]
            b = decoder.decode(baseStr);
            //byte[] 转BufferedImage
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(b);
            image = ImageIO.read(byteArrayInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getText(image);
    }

    /**
     * 解析二维码,此方法解析一个路径的二维码图片
     * path:图片路径
     */
    public static String deEncodeByPath(String path) {
        BufferedImage image = null;
        try {
            image = ImageIO.read(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getText(image);
    }

    /**
     * 生成二维码
     *
     * @param content
     */
    public static void createZingerCode(String content, int width, int height, String filePath) {
        //定义二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        //设置编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置容错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        //设置边距默认是5
        hints.put(EncodeHintType.MARGIN, 2);

        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            Path path = new File(filePath).toPath();
            //写到指定路径下
            MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取内容
     *
     * @param image
     * @return
     */
    private static String getText(BufferedImage image) {
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        //解码
        Result result = null;
        try {
            result = new MultiFormatReader().decode(binaryBitmap, hints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("图片中内容：  ");
        System.out.println("content： " + result.getText());
        return result.getText();
    }
}
